<template>
  <view class="tabs">
    <view class="tabs__header">
      <view 
        v-for="(item, index) in tabs" 
        :key="index"
        class="tabs__item"
        :class="{'tabs__item--active': value === index}"
        @click="handleTabClick(index)"
      >
        {{ item.title }}
      </view>
      <!-- 滑动的下划线 -->
      <view 
        class="tabs__line"
        :style="{
          transform: `translateX(${100 * value}%)`,
          width: `${100/tabs.length}%`
        }"
      >
        <view class="tabs__line-inner"></view>
      </view>
    </view>
    
    <view class="tabs__content">
      <slot></slot>
    </view>
  </view>
</template>

<script>
export default {
  name: 'my-tabs',
  props: {
    // tabs数据
    tabs: {
      type: Array,
      default: () => []
    },
    // 当前选中的索引
    value: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      currentIndex: this.value
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.currentIndex = newVal
      },
      immediate: true
    }
  },
  methods: {
    // 点击tab项
    handleTabClick(index) {
      if (this.currentIndex === index) return
      this.currentIndex = index
      this.$emit('input', index)
      this.$emit('change', index)
    }
  }
}
</script>

<style lang="scss" scoped>
.tabs {
  width: 100%;
  
  &__header {
    position: relative;
    display: flex;
    height: 88rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eee;
  }
  
  &__item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
    position: relative;
    
    &--active {
      color: #2979ff;
      font-weight: bold;
    }
  }
  
  &__line {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 4rpx;
    width: 100%;
    transition: all 0.3s ease-in-out;
    pointer-events: none;
  }

  &__line-inner {
    position: absolute;
    left: 20%;
    right: 20%;
    height: 100%;
    background-color: #2979ff;
    border-radius: 4rpx;
  }
  
  &__content {
    flex: 1;
  }
}
</style> 